﻿
if (!InfoSource) var InfoSource = {};
if (!InfoSource.ManageDoNotMarketList) InfoSource.ManageDoNotMarketList = {};

InfoSource.ManageDoNotMarketList.Map;
InfoSource.ManageDoNotMarketList.MapMarkers = {};
InfoSource.ManageDoNotMarketList.GeoCoder;
InfoSource.ManageDoNotMarketList.ZipCodeIndex = 0;

InfoSource.ManageDoNotMarketList.RenderMap = function () {

	var latlng = new google.maps.LatLng(38.98, -105.55); //just off center of colorado springs cuz thats the closest to centering the state in the viewport
	var myOptions = {
		zoom: 7,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	var mapContainer = document.getElementById("mapContainer");
	InfoSource.ManageDoNotMarketList.Map = new google.maps.Map(mapContainer,
    myOptions);

	InfoSource.ManageDoNotMarketList.GeoCoder = new google.maps.Geocoder();
	InfoSource.ManageDoNotMarketList.DrawMarkers();
}

/*========================================================================================*/
InfoSource.ManageDoNotMarketList.Init = function () {
	this.RenderMap();

	//LazyLoad.js("http://maps.googleapis.com/maps/api/js?key=AIzaSyC_BeXNT_hWbHr5W0RmdQqjmdReGFMOlRk&sensor=false&callback=InfoSource.ManageDoNotMarketList.mapsLoaded");

}

/*======================================================================================*/
InfoSource.ManageDoNotMarketList.InitHandlers = function () {
    $("#zipsContainer").delegate(".btnDelete", "click", function () {
        var me = this;
        var divContainer = $(this).closest("div.zipContainer")
        var zip = divContainer.attr("zip");
        var city = divContainer.attr("city");
        var url = "/InfoSource/Settings/DeleteSingleDoNotMarketZipCode";

        var ajax_success = function (results) {
            if (results.ResultCode != 1) {
                alert("Delete Failure:\n" + results.ResultMessage);
                divContainer.slideDown();
            }
            else {
                divContainer.remove();
                InfoSource.ManageDoNotMarketList.MapMarkers[zip].setMap(null);
                delete InfoSource.ManageDoNotMarketList.MapMarkers[zip];

                var Options = $("#selAddNew option");
                var ThisZip = parseInt(zip);
                for (var x = 0; x < Options.length; x++) {
                    var Option = Options[x];
                    var OptionZip = parseInt($(Option).val());
                    if (OptionZip > ThisZip)
                        break;
                }

                $("<option value='" + zip + "' city='" + city + "'>"
					+ zip + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + city
				+ "</option>").insertBefore(Option);
            }
        }

        if (confirm("Are you sure you want to delete '" + zip + "' ?")) {
            divContainer.slideUp();

            $.ajax({
                url: url
				, type: "POST"
				, data: { zipcode: zip }
				, success: ajax_success
            });
        }

    });

    /*----------------------------------------------------------------------------*/
    $("#btnAdd").click(function () {
        /*
        1. find zip in list
        2. insert new div with zip (keep handle on that div)
        3. ajax zip back
        1. ajax success then remove zip from selection list
        1. add marker to map
        2. ajax error then popup error and remove #2 div
        */

        var Divs = $("#zipsContainer .zipContainer");
        var Option = $("#selAddNew option:selected");
        var City = Option.attr("city");
        var ThisZip = parseInt(Option.val());
        var url = "/InfoSource/Settings/AddSingleDoNotMarketZipCode";

        /* 1 */
        for (var x = 0; x < Divs.length; x++) {
            var Div = Divs[x];
            var DivZip = parseInt($(Div).attr("zip"));
            if (DivZip > ThisZip)
                break;
        }

        /* 2 */
        var newDiv =
			$("<div class='zipContainer' zip='" + ThisZip + "' city='" + City + "'>"
				+ "<span class='actions'>"
					+ "<button class='btnDelete'>Delete</button>"
				+ "</span>"
				+ "<span class='zipcode'>" + ThisZip + "</span>"
				+ "<span class='city'>" + City + "</span>"
			+ "</div>").insertBefore(Div);

        /* 3.1 */
        var ajax_success = function (results) {
            if (results.ResultCode == 1) {
                Option.remove();

                /* 3.1.1 */
                InfoSource.ManageDoNotMarketList.GeoCodeAddressAndDrawMarker(ThisZip + ", Colorado, USA", ThisZip, City);
            }
            /* 3.2 */
            else {
                alert("There was an error saving the new zipcode. Please try adding again.\nError:" + results.ResultMessage);
                newDiv.remove();
            }
        };

        /* 3.2 */
        var ajax_error = function () {
            alert("There was an error saving the new zipcode. Please try adding again.");
            newDiv.remove();
        };

        /* 3 */
        $.ajax({
            type: "POST"
			, url: url
			, data: { zip: ThisZip }
			, success: ajax_success
			, error: ajax_error
        });

    });


    /*----------------------------------------------------------------------------*/
    $(".zipContainer").on("mouseover", function () {
        var zipCode = $(this).attr("zip");

        var Marker = InfoSource.ManageDoNotMarketList.MapMarkers[zipCode];
        if (Marker == null) return;

        Marker.setIcon("/InfoSource/Content/Images/icon_no_large.png");


    });

    /*----------------------------------------------------------------------------*/
    $(".zipContainer").on("mouseout", function () {
        var zipCode = $(this).attr("zip");

        if (InfoSource.ManageDoNotMarketList.MapMarkers[zipCode] == null) return;

        InfoSource.ManageDoNotMarketList.MapMarkers[zipCode].setIcon("/InfoSource/Content/Images/icon_no.png");

    });

    /*----------------------------------------------------------------------------*/
    $("#btn_manageDoNotMarketListPage_printableOutput").on("click", function () {
        var outputType = $("#sel_manageDoNotMarketListPage_PrintableOutputType").val();
        window.open("/InfoSource/Tools/GetPrintableDoNotMarketList?outputType=" + outputType);
    });
}

/*======================================================================================*/
InfoSource.ManageDoNotMarketList.DrawMarkers = function() {
	for (var key in InfoSource.ManageDoNotMarketList.MapMarkers) {
		InfoSource.ManageDoNotMarketList.MapMarkers[key].setMap(null);
		delete InfoSource.ManageDoNotMarketList.MapMarkers[key]
	}

	var Markers = InfoSource.ManageDoNotMarketList.MapMarkers;

	var zipCodes = InfoSource.ManageDoNotMarketList.ZipCodes;

	for (var x in zipCodes) {
		var zipCode = zipCodes[x];
		InfoSource.ManageDoNotMarketList.DrawSingleMarker(x, zipCode.Lat, zipCode.Long, zipCode.City);
	}
}

/*======================================================================================*/
InfoSource.ManageDoNotMarketList.DrawSingleMarker = function(ZipCode, Lat, Long, City) {
	var Markers = InfoSource.ManageDoNotMarketList.MapMarkers;
	
	var marker = new google.maps.Marker(
		{
			position: new google.maps.LatLng(Lat, Long)
			, map: InfoSource.ManageDoNotMarketList.Map
			, title: ZipCode + " - " + City
			, icon: "/InfoSource/Content/Images/icon_no.png"
		}
	);

	Markers[ZipCode] = marker;
}

/*======================================================================================*/
InfoSource.ManageDoNotMarketList.GeoCodeAddressAndDrawMarker = function(address, ZipCode, City) {
	InfoSource.ManageDoNotMarketList.GeoCoder.geocode({ 'address': address}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			var location = results[0].geometry.location;
			InfoSource.ManageDoNotMarketList.DrawSingleMarker(ZipCode, location.Ha, location.Ia, City);
		}
		else {
			alert("Geocode was not successful for the following reason: " + status);
		}
	});
}




/*======================================================================================*/
$(document).ready(function () {
	var onContainerReady = function () {
		InfoSource.ManageDoNotMarketList.Init();
		InfoSource.ManageDoNotMarketList.InitHandlers();
	};

	var containerCheck = function () {
		var container = $("#manageDoNotMarketListPage");

		if (container.length > 0) {
			window.clearInterval(containerCheckTimerForInit);
			onContainerReady();
		}
	};

	var containerCheckTimerForInit = window.setInterval(containerCheck, 100);
});

